package com.hectopascal.goalance.service;

import com.hectopascal.goalance.pojo.WorkContent;
import com.hectopascal.goalance.pojo.dto.WorkContentBack;
import com.hectopascal.goalance.repository.WorkContentRepository;
import com.hectopascal.goalance.service.Ipml.IWorkContentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class WorkContentService implements IWorkContentService {
    @Autowired
    WorkContentRepository workContentRepository;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.upload-dir.documents}")
    private String uploadDirDocuments;

    @Override
    public WorkContentBack workContentAdd(WorkContent workContent){
        WorkContentBack workContentBack = new WorkContentBack();
        WorkContent workContent1 = workContentRepository.save(workContent);
        BeanUtils.copyProperties(workContent1, workContentBack);
        workContentBack.setStatus("pending");
        return workContentBack;
    }

    @Override
    public List<WorkContentBack> workContentGet(Integer userId,String status,Integer departmentId){
        System.out.println(departmentId);
        List<WorkContentBack> workContents = workContentRepository.getAllWorkContent(userId,status,departmentId);
        System.out.println(departmentId);
        return workContents;
    }

    @Override
    public int workContentApprove(WorkContent workContent){
        int rows=workContentRepository.workContentApprove(workContent.getId(),workContent.getStatus(), workContent.getComment());
        return rows;
    }

    @Override
    public String uploadsFile(MultipartFile file, Integer id) throws IOException {
        String endName;
        if(file.getOriginalFilename().contains(".docx")){
            endName=".docx";
        }else if(file.getOriginalFilename().contains(".doc")){
            endName=".doc";
        } else{
            endName=".txt";
        }
        String fileName= UUID.randomUUID().toString() + "_" + id;
        String filePath= uploadDirDocuments + "/" + fileName + endName;
        File dest = new File(filePath);
        file.transferTo(dest.getAbsoluteFile());
        workContentRepository.updateAttachment(filePath, id);
        return filePath;
    }
}
